import { TabContainer } from '@cydon/ui/components'
import { CydonOf } from 'cydon'
import { error, onHashChange } from '../utils'
import { API } from '../api'
import { success } from '@cydon/ui/Message'

/** 登录对话框 */
export class LoginDialog extends CydonOf(TabContainer) {
	/** 是否保持登录 */
	keep = false
	/** 用户名 */
	name = ''
	/** 密码 */
	pwd = ''

	connectedCallback() {
		onHashChange(hash => this.updateTab(hash))
		super.connectedCallback()
	}

	/** 更新选项卡 */
	updateTab(hash: string) {
		if ((<HTMLDialogElement>this.parentNode).open)
			this.select(+(hash == 'reg'))
	}

	/** 登录 */
	login(e: Event) {
		e.preventDefault()
		API.log(this.name, this.pwd).then(token => {
			if (token) {
				e.target!.dispatchEvent(new CustomEvent('user-login', {
					bubbles: true,
					detail: { name: this.name, token, keep: this.keep }
				}))
				this.pwd = ''
			}
		}, error)
	}

	/** 注册 */
	reg(e: Event) {
		e.preventDefault()
		const btn = <HTMLButtonElement>e.target,
			fd = new FormData(btn.form!),
			name = <string>fd.get('name')
		if (name != name.trim())
			error('用户名首尾不能有空格')
		const pwd = <string>fd.get('pwd')
		if (pwd != fd.get('pwd2'))
			error('两次输入的密码不一致')
		if (new Set(pwd).size < 3)
			error('密码过于简单')
		API.reg(name, <string>fd.get('email'), pwd).then((token) => {
			success('注册成功')
			btn.dispatchEvent(new CustomEvent('user-login', {
				bubbles: true,
				detail: { name, token, keep: this.keep }
			}))
		}, error)
	}
}
customElements.define('login-dialog', LoginDialog)

declare global {
	interface HTMLElementTagNameMap {
		'login-dialog': LoginDialog
	}
	interface HTMLElementEventMap {
		'user-login': CustomEvent<{ name: string, token: string, keep: boolean }>
	}
}
